<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>商家资料</span>
        <el-button
            v-if="!isEdit"
            type="primary"
            @click="handleEdit"
        >
          编辑
        </el-button>
      </div>
    </template>

    <!-- 只读展示 -->
    <el-row v-if="!isEdit" :gutter="40">
      <el-col :span="14">
        <div class="info-section">
          <h3 class="title">商家信息</h3>
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span class="label">商家名称：</span>
            <span class="value">{{ merchant.merchantName }}</span>
          </div>
          <div class="info-item">
            <el-icon><Avatar /></el-icon>
            <span class="label">联系人：</span>
            <span class="value">{{ merchant.contactPerson }}</span>
          </div>
          <div class="info-item">
            <el-icon><Phone /></el-icon>
            <span class="label">联系电话：</span>
            <span class="value">{{ merchant.contactPhone }}</span>
          </div>
          <div class="info-item">
            <el-icon><Location /></el-icon>
            <span class="label">商家地址：</span>
            <span class="value">{{ merchant.address }}</span>
          </div>
          <div class="info-item desc">
            <el-icon><Document /></el-icon>
            <span class="label">商家简介：</span>
            <span class="value">{{ merchant.description }}</span>
          </div>
        </div>
      </el-col>

      <el-col :span="10">
        <div class="img-section">
          <div class="img-box">
            <span class="sub-title">店铺 Logo</span>
            <el-image
                :src="`/api/file/download.do?filename=${encodeURIComponent(merchant.logoUrl)}`"
                fit="cover"
                class="avatar-circle"
            />
          </div>
          <div class="img-box">
            <span class="sub-title">营业执照</span>
            <el-image
                :src="`/api/file/download.do?filename=${encodeURIComponent(merchant.businessLicense)}`"
                fit="cover"
                class="avatar-rectangle"
            />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 编辑表单 -->
    <el-form
        v-else
        ref="editFormRef"
        :model="editForm"
        :rules="profileRules"
        label-width="110px"
        size="large"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商家名称" prop="merchantName">
            <el-input v-model="editForm.merchantName" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="editForm.contactPerson" />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="editForm.contactPhone" />
          </el-form-item>
          <el-form-item label="商家地址" prop="address">
            <el-input v-model="editForm.address" />
          </el-form-item>
          <el-form-item label="商家简介" prop="description">
            <el-input v-model="editForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <!-- Logo -->
          <el-form-item label="店铺 Logo" prop="logoUrl">
            <el-upload
                :http-request="uploadLogo"
                list-type="picture-card"
                :file-list="logoFileList"
                :limit="1"
                :on-exceed="() => ElMessage.warning('只能上传一张 Logo')"
                :before-upload="beforeImageUpload"
                :on-preview="handleImagePreview"
                :on-remove="handleLogoRemove"
                accept="image/*"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <!-- 营业执照 -->
          <el-form-item label="营业执照" prop="businessLicense">
            <el-upload
                :http-request="uploadLicense"
                list-type="picture-card"
                :file-list="licenseFileList"
                :limit="1"
                :on-exceed="() => ElMessage.warning('只能上传一张执照')"
                :before-upload="beforeImageUpload"
                :on-preview="handleImagePreview"
                :on-remove="handleLicenseRemove"
                accept="image/*"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Plus,
  User,
  Avatar,
  Phone,
  Location,
  Document
} from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { useMerchantInfoStore } from '@/stores/merchantInfo'
import { getMerchantProfile, updateMerchantProfile } from '@/api/merchant'
import axios from 'axios'
const merchantStore = useMerchantInfoStore()
const merchantId = merchantStore.merchantInfo?.id || ''

const route = useRoute()
const router = useRouter()


/* ----------------- 状态 ----------------- */
const isEdit  = ref(false)
const saving  = ref(false)
const editFormRef = ref()

/* ----------------- 数据模型 ----------------- */
const merchant = reactive({
  id: null,
  merchantName: '',
  contactPerson: '',
  contactPhone: '',
  address: '',
  description: '',
  logoUrl: '',
  businessLicense: ''
})

const editForm = reactive({ ...merchant })   // 初始值在 onMounted 中填充

/* ----------------- el-upload 文件列表 ----------------- */
const logoFileList    = ref([])
const licenseFileList = ref([])

/* ----------------- 校验规则 ----------------- */
const profileRules = {
  merchantName: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 30, message: '商家名称 2-30 个字符', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '联系人 2-20 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入商家地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度 5-100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商家简介', trigger: 'blur' },
    { min: 10, max: 500, message: '简介长度 10-500 个字符', trigger: 'blur' }
  ],
  logoUrl: [
    { required: true, message: '请上传店铺 Logo', trigger: 'change' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ]
}
/* ----------------- 工具：提取纯文件名 ----------------- */
const extractFileName = (path = '') => path.split(/[/\\]/).pop() || ''

/* ----------------- 通用上传方法 ----------------- */
const beforeImageUpload = file => {
  const isImg  = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImg)  ElMessage.error('只能上传图片')
  if (!isLt2M) ElMessage.error('图片不能大于2MB')
  return isImg && isLt2M
}

const doUpload = async file => {
  const fd = new FormData()
  fd.append('file', file)
  const { data } = await axios.post('/api/file/upload1.do', fd)
  // 兼容两种返回格式
  // 1. { data: 'xxx.jpg' }
  // 2. 'xxx.jpg'
  // const fileName =
  //     typeof data === 'string'
  //         ? data
  //         : data?.data || data?.filename || data?.url || data?.message
  const fileName = data.message
  if (!fileName || typeof fileName !== 'string') {
    throw new Error('上传接口未返回文件名')
  }
  return fileName
}
/* ----------------- el-upload 自定义上传 ----------------- */
const uploadLogo = async ({ file, onSuccess, onError }) => {
  try {
    const name = await doUpload(file)
    editForm.logoUrl = name
    onSuccess(name)
  } catch (e) {
    onError(e)
    ElMessage.error('Logo 上传失败')
  }
}

const uploadLicense = async ({ file, onSuccess, onError }) => {
  try {
    const name = await doUpload(file)
    editForm.businessLicense = name
    onSuccess(name)
  } catch (e) {
    onError(e)
    ElMessage.error('执照上传失败')
  }
}

/* ----------------- 预览 / 删除 ----------------- */
const handleImagePreview = ({ url }) => window.open(url, '_blank')
const handleLogoRemove    = () => { editForm.logoUrl = ''; logoFileList.value = [] }
const handleLicenseRemove = () => { editForm.businessLicense = ''; licenseFileList.value = [] }

/* ----------------- 加载商家资料 ----------------- */
const loadMerchantProfile = async () => {
  if (!merchantId) {
    ElMessage.error('无法获取商家ID')
    router.push('/login')
    return
  }

  try {
    const res = await getMerchantProfile(merchantId)
    const d = res?.data || {}
    Object.assign(merchant, d)
    Object.assign(editForm, d)

    // 回显 Logo
    if (d.logoUrl) {
      const fileName = extractFileName(d.logoUrl)
      editForm.logoUrl = merchant.logoUrl = fileName
      logoFileList.value = [{
        name: 'logo',
        url: `/api/file/download.do?filename=${encodeURIComponent(fileName)}`
      }]
    }

    // 回显营业执照
    if (d.businessLicense) {
      const fileName = extractFileName(d.businessLicense)
      editForm.businessLicense = merchant.businessLicense = fileName
      licenseFileList.value = [{
        name: 'license',
        url: `/api/file/download.do?filename=${encodeURIComponent(fileName)}`
      }]
    }
  } catch (e) {
    ElMessage.error('加载失败：' + (e.message || '未知错误'))
  }
}

/* ----------------- 编辑 / 保存 / 取消 ----------------- */
const handleEdit   = () => (isEdit.value = true)
const handleCancel = () => (isEdit.value = false)

const handleSave = async () => {
  await editFormRef.value.validate()
  saving.value = true
  await updateMerchantProfile({ id: merchantId, ...editForm })
  Object.assign(merchant, editForm)
  merchantStore.setMerchantInfo({ id: merchantId, ...editForm })
  isEdit.value = false
  ElMessage.success('资料已更新')
  saving.value = false
}

/* ----------------- 生命周期 ----------------- */
onMounted(loadMerchantProfile)
</script>

<style scoped>
.page-container {
  max-width: 1200px;
  margin: 0 auto;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info-section .title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
}
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 15px;
}
.info-item .label {
  color: #606266;
  margin-left: 8px;
  min-width: 80px;
}
.info-item .value {
  color: #303133;
  font-weight: 500;
}
.img-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
  align-items: center;
}
.sub-title {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #909399;
}
.avatar-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 2px solid #dcdfe6;
  box-shadow: 0 2px 8px rgba(0,0,0,.08);
}
.avatar-rectangle {
  width: 200px;
  height: 120px;
  border-radius: 6px;
  border: 2px solid #dcdfe6;
  box-shadow: 0 2px 8px rgba(0,0,0,.08);
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>